package edu.zju;

import java.sql.Connection;
import java.sql.Statement;
import java.text.SimpleDateFormat;

import net.tinyos.message.Message;
import net.tinyos.message.MessageListener;
import net.tinyos.message.MoteIF;
import net.tinyos.packet.BuildSource;
import net.tinyos.packet.PhoenixSource;
import net.tinyos.tools.PrintLuo6;
import net.tinyos.tools.PrintfMsg;
import net.tinyos.util.PrintStreamMessenger;
import edu.zju.db.MysqlUtil;

public class DBPrintfClient implements MessageListener {

	private MoteIF moteIF;
	private int USBnumStatic = 0;
	private int hum, tem, light;

	char[] strtemp = new char[30];//
	String str;// pay attention!!

	public DBPrintfClient(MoteIF moteIF, int usbnumstatic) {
		this.moteIF = moteIF;
		this.moteIF.registerListener(new PrintfMsg(), this);
		this.USBnumStatic = usbnumstatic;
	}

	public void insertDB(String hum, String tem, String light) {
		SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
		String curtime = formater.format(new java.util.Date());

		Connection conn = MysqlUtil.getConnection(); // FIXME: if conn == null?
		Statement stat = null;
		try {
			stat = conn.createStatement();
			String sql = "INSERT INTO sensor" + USBnumStatic
					+ " (usbnum,hum,tem,light,time) VALUES ( " + USBnumStatic
					+ ", " + hum + ", " + tem + ", " + light + ",  '" + curtime
					+ "');";
			stat.executeUpdate(sql);
		} catch (Exception e) {
			System.err.println(e.getClass().getName() + ":" + e.getMessage());
			System.exit(0);
		} finally {
			MysqlUtil.close(conn, stat);
		}
	}

	public void messageReceived(int to, Message message) {
		PrintfMsg msg = (PrintfMsg) message;
		for (int i = 0; i < PrintfMsg.totalSize_buffer(); i++) {
			char nextChar = (char) (msg.getElement_buffer(i));
			if (nextChar != 0) {
				// System.out.print(nextChar);
				strtemp[i] = nextChar;
			}
		}
		str = char2String(strtemp);
		String str1[] = str.split("@");

		String a = str1[0];
		String b = str1[1];
		String c = str1[2];
		insertDB(a, b, c);
	}

	private static void usage() {
		System.err.println("usage: PrintfClient [-comm <source>]");
	}

	public void mainfunction(String args1, String args2) throws Exception {
		String source = null;
		int USBnum = 0;
		if (!args1.equals("-comm")) {
			usage();
			System.exit(1);
		}
		source = args2;
		if (source.charAt(19) != ':') {
			USBnum += source.charAt(19) - '0';
			USBnum += (source.charAt(18) - '0') * 10;
		} else {
			USBnum = source.charAt(18) - '0';
		}

		PhoenixSource phoenix;
		if (source == null) {
			phoenix = BuildSource.makePhoenix(PrintStreamMessenger.err);
		} else {
			phoenix = BuildSource.makePhoenix(source, PrintStreamMessenger.err);
		}
		System.out.print(phoenix);
		MoteIF mif = new MoteIF(phoenix);
		PrintLuo6 client = new PrintLuo6(mif, USBnum);
	}
	
	private String char2String(char[] c) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < c.length; i++) {
			sb = sb.append(c[i]);
		}
		return sb.toString();
	}
}
